package com.winning.vsts.merge.service.service;

import com.google.common.collect.Sets;
import com.winning.vsts.merge.service.domain.VstsRequest;
import com.winning.vsts.merge.service.domain.WorksItem;
import com.winning.vsts.merge.service.entity.WorkItemDO;
import com.winning.vsts.merge.service.jpa.VstsRequestJpaRepository;
import com.winning.vsts.merge.service.jpa.WorksItemJpaRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * 工作项信息
 *
 * @author xcl <xcl@winning.com.cn>
 * @date 2021/11/18
 */
@Service
public class WorksItemService {


    @Autowired
    private VstsRequestJpaRepository vstsRequestJpaRepository;

    @Autowired
    private WorksItemJpaRepository worksItemJpaRepository;


    @Transactional(rollbackFor = Exception.class)
    public void saveRequestItem(List<WorkItemDO> workItemDos) {
        int size = workItemDos.size();
        Set<String> requestIds = Sets.newHashSetWithExpectedSize(size);
        for (WorkItemDO workItemdo : workItemDos) {
            // 任务就是需求
            WorksItem worksItem = workItemdo.createWorksItem();
            worksItemJpaRepository.save(worksItem);
            if ("需求".equals(workItemdo.getItemType()) && !requestIds.contains(workItemdo.getItemId())) {
                requestIds.add(workItemdo.getItemId());
                VstsRequest request = workItemdo.createRequestByItem();
                saveVstsRequest(request);
            }
            String requestId = worksItem.getRequestId();
            if (StringUtils.isNotEmpty(requestId) && !requestIds.contains(workItemdo.getItemId())) {
                requestIds.add(workItemdo.getItemId());
                VstsRequest request = workItemdo.createRequest();
                saveVstsRequest(request);
            }
        }
    }


    private void saveVstsRequest(VstsRequest vstsRequest) {
        String vstsId = vstsRequest.getVstsId();
        VstsRequest current = vstsRequestJpaRepository.findByVstsId(vstsId);
        if (Objects.isNull(current)) {
            vstsRequestJpaRepository.save(vstsRequest);
        }
    }


}
